from django import forms
from django.contrib.auth.models import User
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Row, Column, Field
from .models import Project
from apps.accounts.models import College


class ProjectForm(forms.ModelForm):
    """项目创建和编辑表单"""
    
    class Meta:
        model = Project
        fields = [
            'name', 'description', 'semester', 'budget', 'admin_manager',
            'project_start_date', 'midterm_check_date', 'project_end_date'
        ]
        widgets = {
            'description': forms.Textarea(attrs={'rows': 4, 'class': 'form-control'}),
            'budget': forms.NumberInput(attrs={'step': '0.01', 'class': 'form-control'}),
            'semester': forms.TextInput(attrs={
                'placeholder': '2024-2025-1',
                'class': 'form-control'
            }),
            'project_start_date': forms.DateInput(attrs={
                'type': 'date',
                'class': 'form-control'
            }),
            'midterm_check_date': forms.DateInput(attrs={
                'type': 'date',
                'class': 'form-control'
            }),
            'project_end_date': forms.DateInput(attrs={
                'type': 'date',
                'class': 'form-control'
            }),
        }
        labels = {
            'name': '项目名称',
            'description': '项目描述',
            'semester': '学期',
            'budget': '项目经费',
            'admin_manager': '教务负责人',
            'project_start_date': '立项时间',
            'midterm_check_date': '中期检查时间',
            'project_end_date': '结项时间',
        }

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        
        # 根据用户角色限制教务负责人选择
        if user and hasattr(user, 'userprofile'):
            if user.userprofile.role == 'admin':
                # 管理员可以选择所有管理员用户
                admin_users = User.objects.filter(userprofile__role='admin')
                self.fields['admin_manager'].queryset = admin_users
            else:
                # 二级学院用户只能选择管理员
                admin_users = User.objects.filter(userprofile__role='admin')
                self.fields['admin_manager'].queryset = admin_users
        
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Field('name', css_class='form-group mb-3'),
            Field('description', css_class='form-group mb-3'),
            Row(
                Column('semester', css_class='form-group col-md-6 mb-3'),
                Column('budget', css_class='form-group col-md-6 mb-3'),
            ),
            Field('admin_manager', css_class='form-group mb-3'),
            Row(
                Column('project_start_date', css_class='form-group col-md-4 mb-3'),
                Column('midterm_check_date', css_class='form-group col-md-4 mb-3'),
                Column('project_end_date', css_class='form-group col-md-4 mb-3'),
            ),
            Submit('submit', '保存项目', css_class='btn btn-primary')
        )

    def clean(self):
        cleaned_data = super().clean()
        semester = cleaned_data.get('semester')
        budget = cleaned_data.get('budget')
        
        # 验证学期格式
        if semester:
            import re
            if not re.match(r'^\d{4}-\d{4}-[12]$', semester):
                raise forms.ValidationError('学期格式错误，应为: YYYY-YYYY-N (如: 2024-2025-1)')
        
        # 验证预算为正数
        if budget and budget <= 0:
            raise forms.ValidationError('项目经费必须大于0')
        
        return cleaned_data


class ProjectSearchForm(forms.Form):
    """项目搜索表单"""
    
    search = forms.CharField(
        max_length=100, 
        required=False,
        widget=forms.TextInput(attrs={
            'placeholder': '搜索项目名称或描述...',
            'class': 'form-control'
        }),
        label='搜索关键词'
    )
    
    semester = forms.CharField(
        max_length=20,
        required=False,
        widget=forms.TextInput(attrs={
            'placeholder': '2024-2025-1',
            'class': 'form-control'
        }),
        label='学期'
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'get'
        self.helper.layout = Layout(
            Row(
                Column('search', css_class='form-group col-md-5 mb-3'),
                Column('semester', css_class='form-group col-md-5 mb-3'),
                Column(
                    Submit('submit', '搜索', css_class='btn btn-primary text-white w-100'), 
                    css_class='form-group col-md-2 mb-3 search-button-container'
                ),
            )
        )


class SubProjectDetailSearchForm(forms.Form):
    """项目详情页面子项目搜索表单"""
    
    search = forms.CharField(
        max_length=100, 
        required=False,
        widget=forms.TextInput(attrs={
            'placeholder': '搜索子项目名称...',
            'class': 'form-control'
        }),
        label='子项目名称'
    )
    
    college = forms.ModelChoiceField(
        queryset=College.objects.all(),
        required=False,
        empty_label='全部学院',
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='所属学院'
    )
    
    manager = forms.CharField(
        max_length=100,
        required=False,
        widget=forms.TextInput(attrs={
            'placeholder': '搜索负责人姓名...',
            'class': 'form-control'
        }),
        label='负责人'
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'get'
        self.helper.layout = Layout(
            Row(
                Column('search', css_class='form-group col-md-4 mb-3'),
                Column('college', css_class='form-group col-md-4 mb-3'),
                Column('manager', css_class='form-group col-md-4 mb-3'),
            )
        )